package com.zjh.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.zjh.admin.service.SysConfigService;
import com.zjh.common.entity.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/Admin/sysConfig")
public class SystemController {

    @Resource
    private SysConfigService sysConfigService;

    @GetMapping("/getSysConfig")
    public Response<String> getConfigByName(@RequestParam String configName) {

        String conf = sysConfigService.getConfigByConfigName(configName);
        if (StringUtils.isNotBlank(conf)) {
            return Response.success(conf);
        } else {
            return Response.error("无此配置");
        }
    }

    @PostMapping("/saveOrUpdateSysConfig")
    public Response<String> saveOrUpdateSysConfig(@RequestBody Map<String, Object> config) {
        try {
            String configName = config.get("configName").toString();
            String configValue = JSONObject.toJSONString(config.get("configValue"));

            sysConfigService.saveOrUpdateConfigByConfigName(configName, configValue);
            return Response.success(configValue);
        } catch (Exception e) {
            log.error("更新或插入配置失败", e);
            return Response.error("更新或插入配置失败");
        }
    }

    @PostMapping("/deleteSysConfig")
    public Response<?> deleteSysConfig(@RequestParam String ConfigName) {
        try {
            sysConfigService.deleteConfigByConfigName(ConfigName);
            return Response.success("删除成功");
        } catch (Exception e) {
            log.error("删除失败", e);
            return Response.success("删除失败");
        }
    }
}
